<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="/layui/css/layui.css">
  <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<div class="panel panel-default operation_user" hidden>
  <div class="panel-heading title"></div>
  <div class="layui-card-body">
    <form class="layui-form " action="" lay-filter="deptInfo" style="width: 700px;margin-top: 10px">
      <input name="id" hidden/>
      <input name="deptId" hidden/>

      <div class="layui-form-item">
        <label class="layui-form-label">账号</label>
        <div class="layui-input-block">
          <input type="text" name="username" placeholder="请输入账号" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-form-label ">密码</div>
        <div class="layui-input-block">
          <input type="text" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-form-label ">手机号</div>
        <div class="layui-input-block">
          <input type="text" name="phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-form-label ">所属部门</div>
        <div class="layui-input-block">
          <input type="text" name="deptName" placeholder="请选择所属部门" autocomplete="off" class="layui-input"
                 readonly="readonly" style="background:#eeeeee!important">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
          <input type="checkbox" name="status" lay-skin="switch" lay-filter="switch" lay-text="启用|禁用" checked>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-input-block">
          <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存</button>
          <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
        </div>
      </div>
    </form>
  </div>
</div>
<div class="user_table_div">
  <div id="searchParam" shiro:hasPermission="sys:user:list">
    <div class="layui-form-item">
      <div class="layui-input-inline">
        <input type="text" id="userId" class="layui-input" autocomplete="off" placeholder="请输入用户ID">
      </div>
      <div class="layui-input-inline">
        <input type="text" id="username" class="layui-input" autocomplete="off" placeholder="请输入账号">
      </div>
      <div class="layui-input-inline">
        <input type="text" id="nickName" class="layui-input" autocomplete="off" placeholder="请输用户昵称">
      </div>
      <div class="layui-input-inline">
        <input type="text" class="layui-input" id="createTime" placeholder="创建时间">
      </div>
      <div class="layui-input-inline layui-form">
        <select id="status">
          <option value="">请选择账号状态</option>
          <option value="1">正常</option>
          <option value="2">禁用</option>
        </select>
      </div>
      <div class="layui-input-inline ">
        <button class="layui-btn" id="search">查询</button>
      </div>
    </div>

  </div>
  <table class="layui-hide" id="user_table" lay-filter="user_table"></table>
  <div id="laypage" class="layui-laypage-btn"></div>
</div>
<div id="deptTree" style="display: none"></div>
<div id="roles" class="demo-transfer" style="display: none"></div>
</body>
<script type="text/html" id="toolbar">
  <div class="layui-btn-group">
    <button type="button" class="layui-btn" lay-event="addNewUser" shiro:hasPermission="sys:user:add">
      <i class="layui-icon">&#xe608;</i> 新增用户
    </button>
  </div>
  <div class="layui-btn-group">
    <button type="button" class="layui-btn" lay-event="batchDeleted" shiro:hasPermission="sys:user:delete">
      <i class="layui-icon">&#xe608;</i> 批量删除
    </button>
  </div>
</script>
<script type="text/html" id="tool">
  <a class="layui-btn  layui-btn-xs" lay-event="operationRole" shiro:hasPermission="sys:user:role:update">赋予角色</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="sys:user:update">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sys:user:delete">删除</a>
</script>
<script src="/layui/layui.js"></script>
<script src="/js/core.util.js"></script>
<script>
  layui.use(['jquery', 'table', 'laypage', 'laydate', 'form', 'tree', 'layer', 'transfer'], function () {
    var $ = layui.jquery;
    var table = layui.table;
    var laypage = layui.laypage;
    var laydate = layui.laydate;
    var form = layui.form;
    var tree = layui.tree;
    var layer = layui.layer;
    var transfer = layui.transfer;
    var searchParam = {
      pageNum: 1,
      pageSize: 10,
      username: null,
      userId: null,
      status: null,
      startTime: null,
      endTime: null,
      nickName: null
    }
    /*记录部门树选中的节点*/
    var selectNode = null;
    CoreUtil.sendAjax("/api/users", JSON.stringify(searchParam), function (res) {
      laypageTable(res.data.totalRows, searchParam.pageNum);
      if (res.data.list != null) {
        loadTable(res.data.list);
      }
    }, "POST", false, function (res) {
      //用户列表接口无权限回调
      layer.msg("抱歉！您暂无获取用户列表的权限");
      var noAuthorityData = [];
      loadTable(noAuthorityData);
    });

    //渲染分页插件
    var laypageTable = function (count, currentPage) {
      laypage.render({
        elem: 'laypage'
        , count: count
        , limit: searchParam.pageSize
        , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        , curr: location.hash.replace('#!currentPage=', '') //获取起始页
        , hash: 'currentPage' //自定义hash值
        , jump: function (obj, first) {
          if (!first) {
            searchParam.pageNum = obj.curr;
            searchParam.pageSize = obj.limit;
            CoreUtil.sendAjax("/api/users", JSON.stringify(searchParam), function (res) {
              if (res.data.list != null) {
                loadTable(res.data.list);
                laypageTable(res.data.totalRows, searchParam.pageNum);
              }

            }, "POST", false, function (res) {
              //用户列表接口无权限回调
              layer.msg("抱歉！您暂无获取用户列表的权限");
              var noAuthorityData = [];
              loadTable(noAuthorityData);
            });
          }
        }
      });
    };

    //渲染table
    var loadTable = function (data) {
      //展示已知数据
      table.render({
        elem: '#user_table'
        , cols: [
          [
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', title: 'ID', width: 300, sort: true},
            {field: 'username', title: '账号', width: 130},
            {field: 'phone', title: '手机号', width: 130},
            {field: 'deptName', title: '所属公司', width: 120},
            {field: 'realName', title: '真实名称', width: 120},
            {field: 'nickName', title: '昵称', width: 130},
            {field: 'email', title: '邮箱', width: 150},
            {
              field: 'sex', title: '性别', width: 100, templet: function (item) {
                if (item.sex === 1) {
                  return "男";
                }
                if (item.sex === 2) {
                  return "女";
                }
              }
            },
            {
              field: 'createTime', title: '创建时间', minWidth: 120, templet: function (item) {
                return CoreUtil.formattime(item.createTime);
              }
            },
            {
              field: 'updateTime', title: '更新时间', minWidth: 120, templet: function (item) {
                return CoreUtil.formattime(item.updateTime);
              }
            },
            {
              field: 'status', title: '状态', width: 100, templet: function (item) {
                if (item.status === 1) {
                  return '  <input type="checkbox" lay-skin="switch" lay-text="正常|禁用" checked disabled>';
                }
                if (item.status === 2) {
                  return '  <input type="checkbox" lay-skin="switch" lay-text="正常|禁用" disabled>';
                }
              }
            },
            {
              field: 'createWhere', title: '注册涞源', width: 100, templet: function (item) {
                if (item.createWhere === 1) {
                  return "Web";
                }
                if (item.createWhere === 2) {
                  return "Android";
                }
                if (item.createWhere === 3) {
                  return "Ios";
                }
              }
            },
            {width: 300, title: '操作', toolbar: '#tool'}
          ]
        ]
        , data: data
        , even: true
        , limit: data.length
        , limits: [10, 20, 30, 40, 50]
        , toolbar: '#toolbar'

      });
    };

    //表头工具栏事件
    table.on('toolbar(user_table)', function (obj) {
      switch (obj.event) {
        case 'addNewUser':
          $(".title").html("新增用户");
          $(".user_table_div").hide();
          $(".operation_user").show();
          $(".operation_user input[name=id]").val("");
          $(".operation_user input[name=pid]").val("");
          $(".operation_user input[name=username]").val("");
          $(".operation_user input[name=password]").val("");
          $(".operation_user input[name=phone]").val("");
          $(".operation_user input[name=deptName]").val("");
          $(".operation_user input[name=status]").attr('checked', 'checked');
          $(".operation_user input[name=status]").attr('type', 'hidden').val(1);
          var x = document.getElementsByClassName("layui-unselect layui-form-switch");
          x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
          var d = document.getElementsByTagName('em')[0];
          d.firstChild.nodeValue = '启用';
          form.render(); //更新全部
          initTree();
          break;
        case 'batchDeleted':
          var checkStatus = table.checkStatus(obj.config.id);
          var data = checkStatus.data;
          if (data.length == 0) {
            layer.msg("请选择要批量删除的用户");
          } else {
            var userIds = [];
            $(data).each(function (index, item) {
              userIds.push(item.id);
            });
            tipDialog(userIds, "选中的");
          }
          break;
      }
      ;
    });

    //监听指定开关
    form.on('switch(switch)', function () {
      $(".operation_user input[name=status]").attr('type', 'hidden').val(this.checked ? 1 : 2);

    });
    //编辑或新增的界面取消事件
    $("#btn_cancel").click(function () {
      //显示表格
      $(".user_table_div").show();
      //隐藏编辑窗口
      $(".operation_user").hide();
      //可以防止在表单事件操作后自动刷新
      return false;
    });
    var initTree = function () {
      CoreUtil.sendAjax("/api/dept/tree", null, function (res) {
        loadDeptTree(res.data);
      }, "GET", false, function (res) {
        //部门树列表无权限提示
        layer.msg("抱歉！您暂无获取部门树的权限");
        var noAuthorityData = [];
        loadDeptTree(noAuthorityData);
      });
    };
    //加载部门树数据
    var loadDeptTree = function (data) {
      //仅节点左侧图标控制收缩
      tree.render({
        elem: '#deptTree'
        , data: data
        , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
        , click: function (obj) {
          selectNode = obj;
          layer.msg(JSON.stringify(selectNode.data.title));
        }
      });
    };

    //打开部门树对话框
    $(".operation_user input[name=deptName]").click(function () {
      layer.open({
        type: 1,
        offset: '50px',
        skin: 'layui-layer-molv',
        title: "选择部门",
        area: ['400px', '550px'],
        shade: 0,
        shadeClose: false,
        content: $("#deptTree"),
        btn: ['确定', '取消'],
        yes: function (index) {
          if (selectNode.data != null) {
            //选中回显
            $(".operation_user input[name=deptId]").val(selectNode.data.id);
            $(".operation_user input[name=deptName]").val(selectNode.data.title);
          }

          layer.close(index);
        }
      });
    });

    //监听提交
    form.on('submit(submit)', function (data) {
      //新增
      if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
        CoreUtil.sendAjax("/api/user", JSON.stringify(data.field), function (res) {
          //显示表格
          $(".user_table_div").show();
          //隐藏编辑窗口
          $(".operation_user").hide();
          $(".layui-laypage-btn").click();
        }, "POST", false, function (res) {
          //新增用户无权限提示
          layer.msg("抱歉！您暂无新增用户的权限");
        });
      } else {
        CoreUtil.sendAjax("/api/user", JSON.stringify(data.field), function (res) {
          //显示表格
          $(".user_table_div").show();
          //隐藏编辑窗口
          $(".operation_user").hide();
          $(".layui-laypage-btn").click();
        }, "PUT", false, function (res) {
          //更新用户无权限提示
          layer.msg("抱歉！您暂无编辑用户的权限");
        });
      }
      return false;
    });

    //日期范围
    laydate.render({
      elem: '#createTime'
      , type: 'datetime'
      , range: '~'
      , done: function (value, date, endDate) {
        if (value != null && value != undefined && value != "") {
          searchParam.startTime = value.split("~")[0];
          searchParam.endTime = value.split("~")[1];
        } else {
          //清空时间的时候要清空以前选择的日期
          searchParam.startTime = null;
          searchParam.endTime = null;
        }

      }
    });

    //执行查询
    $("#search").click(function () {
      searchParam.userId = $("#userId").val();
      searchParam.status = $("#status").val();
      searchParam.username = $("#username").val();
      searchParam.nickName = $("#nickName").val();
      searchParam.pageNum = 1;
      CoreUtil.sendAjax("/api/users", JSON.stringify(searchParam), function (res) {
        //初始化分页器
        laypageTable(res.data.totalRows, searchParam.pageNum);
        //初始化渲染数据
        if (res.data.list != null) {
          loadTable(res.data.list);
        }
      }, "POST", false, function (res) {
        //用户列表接口无权限回调
        layer.msg("抱歉！您暂无获取用户列表的权限");
        var noAuthorityData = [];
        loadTable(noAuthorityData);
      });
    });
    //操作工具栏事件
    table.on('tool(user_table)', function (obj) {
      var data = obj.data;
      switch (obj.event) {
        case 'operationRole':
          CoreUtil.sendAjax("/api/user/roles/" + data.id, null, function (res) {
            initTransfer(res.data);
            layer.open({
              type: 1,
              offset: '50px',
              skin: 'layui-layer-molv',
              title: "赋予角色",
              area: ['500px', '400px'],
              shade: 0,
              shadeClose: false,
              content: $("#roles"),
              btn: ['确定', '取消'],
              yes: function (index) {
                //获得右侧数据
                var roleIds = [];
                var getData = transfer.getData('ownData');
                // layer.msg(JSON.stringify(getData));
                if (getData.length != 0) {
                  $(getData).each(function (index, item) {
                    roleIds.push(item.value);
                  });
                }
                var param = {
                  userId: data.id,
                  roleIds: roleIds
                }
                CoreUtil.sendAjax("/api/user/roles", JSON.stringify(param), function (res) {
                  layer.msg(res.msg);
                  $(".layui-laypage-btn").click();
                }, "PUT", false, function (res) {
                  //赋予用户角色无权限提示
                  layer.msg("抱歉！您暂无赋予用户角色的权限");
                });
                layer.close(index);
              }
            });
          }, "GET", false, function (res) {
            layer.msg("抱歉！您暂无查询用户所拥有角色列表的权限");
          });
          break;
        case 'edit':
          $(".user_table_div").hide();
          $(".operation_user").show();
          $(".title").html("编辑用户");
          $(".operation_user input[name=id]").val(data.id);
          $(".operation_user input[name=deptId]").val(data.deptId);
          $(".operation_user input[name=username]").val(data.username);
          $(".operation_user input[name=password]").val("");
          $(".operation_user input[name=phone]").val(data.phone);
          $(".operation_user input[name=deptName]").val(data.deptName);
          if (data.status == 1) {
            $(".operation_user input[name=status]").attr('checked', 'checked');
            $(".operation_user input[name=status]").attr('type', 'hidden').val(1);
            var x = document.getElementsByClassName("layui-unselect layui-form-switch");
            x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
            var d = document.getElementsByTagName('em')[0];
            d.firstChild.nodeValue = '启用';
          } else {
            $(".operation_user input[name=status]").attr('type', 'hidden').removeAttr("checked").val(2);
            var x = document.getElementsByClassName("layui-unselect layui-form-switch");
            x[0].setAttribute("class", "layui-unselect layui-form-switch");
            var d = document.getElementsByTagName('em')[0];
            d.firstChild.nodeValue = '禁用';
          }
          form.render(); //更新全部
          initTree();
          break;
        case 'del':
          var userIds = [];
          userIds.push(data.id);
          tipDialog(userIds, data.username);
          break;
      }
    });
    //初始化 赋予角色控件
    var initTransfer = function (data) {
      //显示搜索框
      transfer.render({
        elem: '#roles'
        , data: data.allRole
        , title: ['赋予角色', '拥有角色']
        , showSearch: true
        , value: data.ownRoles
        , id: 'ownData'
        , parseData: function (res) {
          return {
            "value": res.id //数据值
            , "title": res.name //数据标题
          }
        }
      })
    };
    //删除前确认对话框
    var tipDialog = function (userIds, username) {
      layer.open({
        content: '确定要删除' + username + "用户么?",
        yes: function (index, layero) {
          layer.close(index); //如果设定了yes回调，需进行手工关闭
          CoreUtil.sendAjax("/api/user", JSON.stringify(userIds), function (res) {
            layer.msg(res.msg);
            $(".layui-laypage-btn").click();
          }, "DELETE", false, function (res) {
            //删除用户无权限
            layer.msg("抱歉！您暂无删除用户的权限");
          });
        }
      });
    };
  });

</script>
</html>